#version 460
#extension GL_ARB_separate_shader_objects : enable
#extension GL_ARB_shading_language_420pack : enable


layout (location = 0) in vec3 inNormal;
layout (location = 1) in vec2 inUV;
layout (location = 2) in vec3 inWorldPos;
layout (location = 3) in float inCameraNearPlane;
layout (location = 4) in float inCameraFarPlane;
layout (location = 5) in vec4 inColor;
layout (location = 6) in vec3 InViewPos;

layout (location = 0) out vec4 outColor;

float linearDepth(float depth)
{
	float z = depth * 2.0f - 1.0f; 
	return (2.0f * inCameraNearPlane * inCameraFarPlane) / (inCameraFarPlane + inCameraNearPlane - z * (inCameraFarPlane - inCameraNearPlane));	
}

//ref：https://learnopengl.com/PBR/Theory
vec3 GetNormalFromMap(vec3 InNormalTextureValue)
{
    vec3 tangentNormal=InNormalTextureValue*2.0-1.0; // convert from range(0,1) to range(-1,1)
    
    vec3 Q1  = dFdx(inWorldPos);
    vec3 Q2  = dFdy(inWorldPos);
    vec2 st1 = dFdx(inUV);
    vec2 st2 = dFdy(inUV);

    vec3 N   = normalize(inNormal);
    vec3 T  = normalize(Q1*st2.t - Q2*st1.t);
    vec3 B  = -normalize(cross(N, T));
    mat3 TBN = mat3(T, B, N);

    return normalize(TBN * InNormalTextureValue);
}

void main() 
{ 
    outColor=inColor;

    vec3 Normal=GetNormalFromMap(vec3(0,0,1));

    vec3 LightPos=InViewPos + vec3(0,0,100);

    vec3 LightDir=normalize(LightPos-InViewPos);

    float Diffuse=max(dot(Normal,LightDir),0.5);

    outColor.rgb*=Diffuse *2;


}